<script>
// 导入组件
import Player from '@/components/player/player.vue'
import Charge from '@/components/charge/charge.vue'

// 导入APIs
import {
	getApiEpisodeList,
	dyGetEpisodeList,
	getApiVideoList,
	dyUnlockEpisode,
	getApiEpisodeInfo,
	getDyAdEpisodeInfo,
	RewardedVideoAdShow,
	RewardedVideoAdEnd,
	RewardedVideoAdNoEnd,
} from '@/api/teleplay'
import { showMessage } from '@/utils/message'
// 导入工具函数
import { OSSImgUrl, isShowPay } from '@/utils'

// 导入状态管理
import store from '@/store/index'

// 获取播放器管理器
const { PlayletExtension, getPlayletManager } = tt
PlayletExtension()
let CacheEpisodeItem = null
export default {
	components: { Player, Charge },
	data() {
		return {
			pm: null,
			eid: '', // 用户ID
			videoId: 0, // 视频ID
			videoName: '', // 视频名称
			coverUrl: '', // 封面URL
			currentSort: 1, // 当前集数
			DyAdId: '', // 广告ID
			ttAdInstance: null, // 广告实例
			isAdLoading: false, // 广告加载状态
			IsUseAdPay: 1, // 是否使用广告支付
			// IsUseAdPay: store.state.global.IsHasChannelType, // 是否使用广告支付
			episodeList: [], // 剧集列表
			episodeInfo: {}, // 剧集详情
			showCustomDialog: false,
		}
	},
	//采用uniapp的生命周期函数
	onLoad(option) {
		console.log('onLoad option:', option)

		// 获取路由参数
		if (option.video_id) {
			this.videoId = Number(option.video_id) // 确保videoId是数字类型
		}
		if (option.seq) {
			console.log('option.seq', option.seq)
			this.currentSort = Number(option.seq)
			this.episodeInfo.sort = this.currentSort
		}
		uni.setStorageSync('loadOption', option)

		// 获取用户信息并设置eid
		this.getEid()

		// 获取短剧管理器
		const pm = getPlayletManager(this)
		this.pm = pm
		console.error(pm, 'onLoad_pm_vue2')

		// 获取store中的剧集信息，或者从本地存储中获取
		const storeEpisodeInfo = store.state.teleplay.episodeInfo
		this.episodeInfo =
			Object.keys(storeEpisodeInfo).length > 0
				? storeEpisodeInfo
				: uni.getStorageSync('episodeInfo') || {}

		console.log('初始化剧集信息:', this.episodeInfo)
	},
	async onReady() {
		const p_m = getPlayletManager(this)
		this.pm = p_m
		console.error(p_m, 'pm')
		console.log(p_m, 'onReady_pm_vue2')

		// 确保有eid值
		if (!this.eid) {
			console.log('onReady: eid不存在，开始轮询获取')
			this.eid = await this.getEid()
			if (!this.eid) {
				console.warn('onReady: 轮询获取eid失败，可能影响后续操作')
			}
		}

		// 获取视频信息
		if (this.videoId) {
			try {
				const { data } = await getApiVideoList(1, 1, this.videoId)
				if (data && data.list && data.list.length > 0) {
					const videoInfo = data.list[0]
					this.videoName = videoInfo.video_name
					this.coverUrl = videoInfo.cover_url
				}
			} catch (error) {
				console.error('获取视频信息失败', error)
			}
		}

		// 只调用一次getEpisodeList，避免重复请求
		// 确保使用正确的videoId
		console.log('准备获取剧集列表，videoId:', this.videoId)

		// // 如果有缓存的剧集信息，优先使用缓存中的video_id
		if (this.episodeInfo && Object.keys(this.episodeInfo).length > 0) {
			console.log('使用缓存的剧集信息', this.episodeInfo)
			// 使用缓存中的sort
			this.currentSort = this.episodeInfo.sort || this.currentSort
			console.log('this.currentSort', this.currentSort)
			// 确保使用正确的video_id
			if (this.episodeInfo.video_id) {
				this.videoId = Number(this.episodeInfo.video_id)
				console.log('使用缓存中的video_id:', this.videoId)
			}
		}

		// 只调用一次getEpisodeList，避免重复请求
		await this.getEpisodeList()

		// 3. 监听播放相关事件
		p_m.onPlay((e) => {
			console.error('可以播放了，可以播放了，可以播放了，可以播放了', e)

			// 可以添加播放统计埋点
			// trackVideoPlay({
			//   video_id: this.videoId,
			//   episode: e.current,
			//   eid: this.eid
			// });
		})

		p_m.onError((e) => {
			console.error('插件页onload  报错了 报错了', e)
		})

		p_m.onPause((e) => {
			console.error('触发暂停播放onPause回调:', e)
		})

		// 设置解锁点击回调
		p_m.onClickUnlock(async (e) => {
			console.log('点击解锁', e)
			// this.getEpisodeInfo(e.seq, this.videoId)
		})
	},
	onShow() {
		console.log('show', store.state.user.defaultParams.aid)
	},
	mounted() {
		console.error(this, 'this')

		const child = this.$refs.childRef
		console.error(child, this.$refs, 'childRef')
	},
	// 打开分享面板时触发
	onShareAppMessage() {
		// 确保有eid值（虽然分享不一定需要eid，但为了保持一致性）
		if (!this.eid) {
			console.log('分享时检测到eid不存在，尝试获取')
			// 这里不能使用await，所以只能同步获取一次
			try {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo && userInfo.eid) {
					this.eid = userInfo.eid
				}
			} catch (error) {
				console.warn('分享时获取eid失败:', error)
			}
		}

		/**进入小程序携带的参数 */
		const launchData = uni.getLaunchOptionsSync()

		// 将参数转换成字符串携带分享在路径后
		const queryData = this.generateString(launchData.query)
		const share_id = launchData.query.share_id
			? launchData.query.share_id
			: '3fbh0gcm03i517c772'
		return {
			path: `/pages/playlet/index?${queryData}&tt_album_id=${this.episodeInfo.album_id}&tt_episode_id=1`, // ?后面的参数会在转发页面打开时传入onLoad方法
			templateId: share_id, // templateId为开发者后台申请的分享 ID
			title: this.episodeInfo.video_name,
		}
	},
	methods: {
		// 轮询获取eid的方法
		async getEid() {
			return new Promise((resolve) => {
				let count = 0
				const maxTries = 3
				const interval = 500 // 每次尝试间隔500ms

				const tryGetEid = () => {
					if (this.eid) {
						console.log('已获取到eid:', this.eid)
						resolve(this.eid)
						return
					}

					// 尝试从缓存中获取
					try {
						let userInfo = uni.getStorageSync('userInfo')
						// 确保userInfo是对象
						if (typeof userInfo !== 'object') {
							try {
								userInfo = JSON.parse(userInfo)
							} catch (error) {
								console.warn('解析userInfo失败:', error)
								userInfo = {}
							}
						}

						if (userInfo && userInfo.eid) {
							this.eid = userInfo.eid
							console.log('从缓存获取到eid:', this.eid)
							resolve(this.eid)
							return
						}
					} catch (error) {
						console.warn('获取用户信息失败:', error)
					}

					count++
					if (count >= maxTries) {
						console.warn('轮询获取eid失败，已达到最大尝试次数')
						resolve('') // 返回空字符串表示获取失败
						return
					}

					console.log(`尝试获取eid: 第${count}次，将在${interval}ms后重试`)
					setTimeout(tryGetEid, interval)
				}

				tryGetEid()
			})
		},

		// 获取剧集列表
		async getEpisodeList(customVideoId) {
			// 允许传入自定义的videoId，否则使用组件实例上的videoId
			const videoIdToUse = customVideoId || this.videoId

			// 确保有eid值
			if (!this.eid) {
				console.log('eid不存在，开始轮询获取')
				this.eid = await this.getEid()
				if (!this.eid) {
					console.warn('轮询获取eid失败，可能影响后续操作')
				}
			}

			if (!videoIdToUse || !this.eid) {
				console.error('获取剧集列表失败: 缺少videoId或用户eid')
				return
			}

			uni.showLoading({
				title: '加载中',
				mask: true,
			})

			try {
				let episodeData
				// 确保使用正确的videoId格式（数字类型）
				const requestVideoId = Number(videoIdToUse)
				console.log(
					'【剧集列表】请求参数 video_id:',
					requestVideoId,
					'类型:',
					typeof requestVideoId,
					this.IsUseAdPay
				)

				if (this.IsUseAdPay === 1) {
					// 广告支付模式
					console.log('【剧集列表】使用广告支付模式API')
					const { data } = await dyGetEpisodeList({
						video_id: requestVideoId,
						pn: 1,
						ps: 1000,
						eid: this.eid,
					})

					episodeData = data
					if (data.ad_id) {
						this.DyAdId = data.ad_id
						uni.setStorageSync('DyAdId', data.ad_id)
						// this.createAdInstance(data.ad_id)
						console.log('【剧集列表】获取广告ID:', data.ad_id)
					}
				} else {
					// 普通支付模式
					console.log('【剧集列表】使用普通支付模式API')
					const { data } = await getApiEpisodeList(
						requestVideoId,
						1,
						1000,
						this.eid
					)
					episodeData = data
				}

				// 解析剧集数据
				if (episodeData && episodeData.list) {
					this.episodeList = episodeData.list
					uni.setStorageSync('episodeList', episodeData.list)
					// 保存第一集的信息到episodeInfo（重要，修复初始化问题）

					// 构造剧集目录数据
					const freeList = []
					const unlockList = []
					const lockList = []

					this.episodeList.forEach((item) => {
						// 根据剧集状态分类
						if (item.is_vip === 0) {
							// 免费剧集
							freeList.push({
								start_episode_no: item.sort,
								end_episode_no: item.sort,
							})
						} else if (item.is_buy === 1) {
							// 已购买/解锁剧集
							unlockList.push({
								start_episode_no: item.sort,
								end_episode_no: item.sort,
							})
						} else {
							// 未解锁的VIP剧集
							lockList.push({
								start_episode_no: item.sort,
								end_episode_no: item.sort,
							})
						}
					})

					// 合并连续的剧集范围
					const mergeContinuousRanges = (ranges) => {
						if (ranges.length <= 1) return ranges

						ranges.sort((a, b) => a.start_episode_no - b.start_episode_no)

						const result = []
						let current = ranges[0]

						for (let i = 1; i < ranges.length; i++) {
							const range = ranges[i]

							if (range.start_episode_no <= current.end_episode_no + 1) {
								// 合并区间
								current.end_episode_no = Math.max(
									current.end_episode_no,
									range.end_episode_no
								)
							} else {
								// 添加当前区间并开始新区间
								result.push(current)
								current = range
							}
						}

						result.push(current)
						return result
					}

					const mergedFreeList = mergeContinuousRanges(freeList)
					const mergedUnlockList = mergeContinuousRanges(unlockList)
					const mergedLockList = mergeContinuousRanges(lockList)

					// 设置剧集目录
					this.pm.setCatalog({
						freeList: mergedFreeList,
						unlockList: mergedUnlockList,
						lockList: mergedLockList,
					})

					console.log('设置剧集目录:', {
						freeList: mergedFreeList,
						unlockList: mergedUnlockList,
						lockList: mergedLockList,
					})
				}

				uni.hideLoading()
			} catch (error) {
				console.error('获取剧集列表失败', error)
				uni.hideLoading()

				// 设置默认剧集目录
				this.pm.setCatalog({
					freeList: [
						{
							start_episode_no: 1,
							end_episode_no: 5,
						},
					],
					unlockList: [],
					lockList: [
						{
							start_episode_no: 6,
							end_episode_no: 100,
						},
					],
				})
			}
		},

		generateString(obj) {
			// 从请求默认对象中获取
			const aid = store.state.user.defaultParams.aid
			// 如果进入小程序时没有携带参数则使用默认对象
			if (Object.keys(obj).length <= 0) {
				obj = {
					channel_id: uni.getStorageSync('channel_id') || 0,
					video_id: this.episodeInfo.video_id,
					seq: 1,
					form: 99,
					aid,
					share_id: '3fbh0gcm03i517c772',
				}
			}
			const keys = Object.keys(obj)
			const values = Object.values(obj)
			const pairs = keys.map((key, index) => `${key}=${values[index]}`)
			const stringified = pairs.join('&')
			return stringified // 输出：&sort=1&channel_id=211
		},
	},

	beforeDestroy() {
		uni.removeStorageSync('DyAdId')
		uni.removeStorageSync('loadOption')
		if (this.episodeInfo) {
			// console.log('销毁页面', this.episodeInfo, this.currentSort)
			// uni.setStorageSync('recentVideo', {
			// 	...this.episodeInfo,
			// 	sort: this.currentSort,
			// })
		}
	},
}
</script>

<style>
.playlet-wrapper {
	position: relative;
	width: 100%;
	height: 100%;
}
</style>
